package dk.sensobyg.reader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

import dk.sensobyg.base.SensorData;

public class SensorDataReader {
	
	
	public static String pad(String value) {
		if (value.length() == 1) {
			return "0" + value;
		} else {
			return value;
		}
	}
	
	public static String unquote(String value) {
		return value.substring(1, value.length() - 1);
	}
	
	public static String convertDate(String value) {
		String[] values = value.split(" ");
		String[] date = values[0].split("-");
		String[] time = values[1].split(":");
		
		String day = date[0];
		String month = date[1];
		String year = date[2];
		String hour = time[0];
		String min = time[1];
		String sec = "00";
		if (time.length == 3) {
			sec = time[2];
		}
		if (year.length() == 2) {
			year = "20" + year;
		}
		month = pad(month);
		day = pad(day);
		hour = pad(hour);
		min = pad(min);
		sec = pad(sec);
		String result = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
		return result;
	}
	
	public static SensorData parse(String string) {
		String[] pieces = string.split(";");
		String date = pieces[1];
		date = unquote(date);
		date = date.replace('/', '-');
		date = convertDate(date);
		String id = pieces[5];
		id = unquote(id);
		String value = pieces[6];
	    Timestamp time = Timestamp.valueOf(date);
	    long moteid = Long.decode("0x" + id);
	    moteid = moteid & 0xFFFFFF;
	    long temp = Long.valueOf(value);
		SensorData data = new SensorData(moteid, time.getTime(), temp);
		return data;
	}
	
	public List<SensorData> read(String name) throws IOException {
		List<SensorData> result = new LinkedList();
		File file = new File(name);
		BufferedReader input = new BufferedReader(new FileReader(file));
		String header = input.readLine();
		String empty = input.readLine();
		String next = input.readLine();
		while (next != null) {
			SensorData data = parse(next);
			result.add(data);
			next = input.readLine();
		}
		HashSet<Long> ids = new HashSet();
		for (SensorData current : result) {
			ids.add(current.getSensorId());
		}
		for (Long current : ids) {
			System.out.println(current);
		}
		return result;
	}
	
	public static void main(String[] args) {
		SensorDataReader reader = new SensorDataReader();
		try {
			reader.read("bridge-data.csv");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
